﻿using SmartSpace.Web;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

namespace SmartSpace.Template.Prototype
{
    public partial class NavigationPanel : System.Web.UI.UserControl, INavigationPanel
    {
        public event NavigatingEventHandler Navigating;

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        public void Initiate(IEnumerable<Core.Navigation> navigations, IEnumerable<Core.Shortcut> shortcuts)
        {
            Bind(_ctlNavigations, navigations);
        }

        private void Bind(Control parent, IEnumerable<Core.Navigation> navigations)
        {
            foreach (var item in navigations)
            {
                HtmlGenericControl ctlLi = new HtmlGenericControl("li");
                if (!string.IsNullOrEmpty(item.Url))
                {
                    HtmlGenericControl ctlLink = new HtmlGenericControl("a");
                    ctlLink.InnerText = item.Caption;
                    ctlLink.Attributes.Add("href", ConvertUrl(item));
                    ctlLi.Controls.Add(ctlLink);
                }
                else
                {
                    ctlLi.InnerText = item.Caption;
                }
                parent.Controls.Add(ctlLi);

                if (item.Children != null && item.Children.Count > 0)
                {
                    HtmlGenericControl ctlContainer = new HtmlGenericControl("ul");
                    ctlLi.Controls.Add(ctlContainer);
                    Bind(ctlContainer, item.Children);
                }
            }
        }

        private string ConvertUrl(Core.Navigation navigation)
        {
            string url = navigation.Url;
            if (url.StartsWith("~"))
            {
                return this.ResolveClientUrl(url);
            }
            return url;
        }
    }
}